<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-04 16:53:56
 * @LastEditTime: 2023-10-30 12:21:05
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description: 
 */

namespace App\Http\Services\Purchase;

use App\Events\UploadFileEvent;
use App\Http\Services\Service;
use App\Models\Attachment;
use App\Repositories\MarketDeliveryExtraCostRepository;
use App\Repositories\MaterialRepository;
use App\Repositories\PurchaseOrderDetailsRepository;
use App\Repositories\PurchaseOrderRepository;
/**
 * Summary of OrderService
 * @property MarketDeliveryExtraCostRepository $ex_cost
 * @author sunkaiyuan
 */
class OrderService extends Service
    {
    public $details;
    public function __construct(PurchaseOrderRepository $repository, PurchaseOrderDetailsRepository $details, MarketDeliveryExtraCostRepository $ex_cost)
        {
        $this->repository = $repository;
        $this->details    = $details;
        $this->ex_cost    = $ex_cost;
        }
    public function info()
        {
        return $this->repository->condition()->getOne();
        }
    public function list()
        {
        $data = $this->details->condition(request())->getGrid();
        return $data;
        }
    protected function saveAndFinace()
        {
        $data = request()->toArray();

        $code  = $data['code'];
        $gdata = $this->repository->whereCode($code)->getOne();
        if ($gdata->status_id != '1') {
            fail("订单状态[{$gdata->status->name}],禁止审核");
            }
        $ids          = [];
        $extra_amount = 0;
        array_filter($data['extra_cost_details'], function ($v) use ($code, &$ids, &$extra_amount)
            {
            $v['code']    = $code;
            $extra_amount += is_numeric($v['amount']) ? $v['amount'] : 0;
            $ids[]        = $this->ex_cost->autosave($v)->id;
            });
        $this->ex_cost->whereCode($code)->whereNotIn("id", $ids)->get()->filter(function ($v)
            {
            $v->delete();
            });
        $ids = [];
        //合计订单包/重  
        $amount = 0;
        array_map(function ($v) use (&$amount, &$ids, $data)
            {
            $detail_m         = $this->details->whereId($v['id'])->first();
            $detail_m->price  = $v['price'];
            $detail_m->amount = $v['amount'];
            $detail_m->tax_id = $data['tax_id'];
            $detail_m->save();
            $ids[]  = $detail_m->id;
            $amount += $v['amount'];
            }, $data['details']);
        $gdata->amount       = $amount;
        $gdata->billdate     = $data['billdate'];
        $gdata->extra_amount = $extra_amount;
        $gdata->tax_id       = $data['tax_id'];
        $gdata->save();
        return $this->faudit($ids);
        }

    protected function save($request)
        {
        $data = $request->toArray();
        //意外错误！页面未刷新，导致状态不正确！
        unset($data['status_id']);
        if (!isEmpty($request->id)) {
            $gdata = $this->repository->whereId($request->id)->first();
            if ($gdata->status_id === 1) {
                fail("单据【{$request->code}】已审核！禁止编辑");
                }
            }
        if (!is_array($data['details']) || count($data['details']) == 0) {
            fail("明细不能为空！");
            }
        $remark = [];
        foreach ($data['details'] as $k => $v) {
            if (isEmpty($v['price'] ?? "")) {
                fail("单价必须填写！");
                }
            if (!is_numeric($v['material_id'] ?? "") || $v['material_id'] == 0) {
                fail("产品必须选择！");
                }
            if (trim($v['remark'] ?? "") != "") {
                $remark[] = $v['remark'];
                }
            }
        $data['totalremark'] = ($data['remark'] ?? "") . implode("|", $remark);
        $gdata               = $this->repository->autosave($data);
        $count               = 1;
        $gdata->details->filter(function ($v) use ($gdata, &$count)
            {
            $v->location_id = isEmpty($v->location_id) ? 3254 : $v->location_id;
            $v->code        = $gdata->code;
            $v->batchno     = $gdata->code . substr('000' . $count, -2);
            $v->tax_id      = $gdata->tax_id;
            $v->type        = $gdata->type;
            $v->company_id  = $gdata->company_id;
            $v->save();
            });
        }
    protected function audit()
        {
        // event(new UploadFileEvent(Attachment::first()));
        return $this->getOrder()->filter(function ($Order)
            {
            if ($Order->status_id == 1)
                fail("单据【{$Order->code}】已审核！");
            auditSave($Order);
            $Order->details->filter(
                function ($v)
                    {
                    //更新可到货数,type=1 是样品采购，不用入库
                    $v->type != 1 && $v->addStorage("采购来货");
                    auditSave($v);
                    }
            );
            });
        }

    /**
     * Summary of noaudit
     * @return mixed
     */
    protected function noaudit()
        {
        return $this->getOrder()->filter(function ($Order)
            {
            if ($Order->status_id == 0)
                fail("单据【{$Order->code}】未审核！");
            auditSave($Order, false);
            $Order->details->filter(
                function ($v)
                    {
                    $v->type != 1 && $v->noaddStorage();
                    auditSave($v, false);
                    }
            );
            });
        }

    protected function faudit($ids = null)
        {
        $financeremark = request("financeremark");
        $this->getOrder($ids)->filter(function ($order) use ($financeremark)
            {
            if ($order->status_id != 1) {
                fail("单据【{$order->code}】【{$order->status->name}】,审核失败！");
                }
            $order->financeremark = $financeremark;
            $order->details->filter(function ($v) use ($financeremark)
                {
                $v->financeremark = $financeremark;
                $v->save();
                });
            $order->finance();
            });
        }
    public function getOrder($ids = null)
        {
        $ids = $this->details->whereIn("id", $ids ?? $this->getRequestIds())->pluck("main_id");
        return $this->repository->whereIn("id", $ids)->get();
        }
    protected function delete($request)
        {
        $ids = [];
        $this->details->whereIn("id", $this->getRequestIds())->get()->filter(function ($detail) use (&$ids)
            {
            if ($detail->status_id == 1)
                fail("采购订单已审核！");
            $ids[$detail['main_id']] = $detail['main_id'];
            $detail->delete();
            });
        $newids = $this->details->whereIn("main_id", $ids)->pluck("main_id");
        return $this->repository
            ->whereIn("id", $ids)
            ->whereNotIn("id", $newids)->get()->filter(function ($Order)
                {
                $Order->delete();
                });
        ;
        // $this->details->delete($request->input("ids"));
        }

    public function printReport()
        {
        $data = $this->details->relation()->whereIn("id", $this->getRequestIds())->get();
        // dd($data);
        return createReport($data->toArray());
        }
    }